from venv import logger

from django.db import DatabaseError
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import exception_handler


def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)
    if "detail" in response.data:
        del response.data["detail"]
        response.data['err_msg'] = exc.detail
    if "non_field_errors" in response.data:
        del response.data["non_field_errors"]
        response.data['err_msg'] = exc.detail
    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code
    if response is None:
        view = context['view']
        if isinstance(exc, DatabaseError):
            # 数据库异常
            logger.error('[%s] %s' % (view, exc))
            response = Response({'message': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

    return response
